package com.markerhub.common.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.markerhub.common.ResponseCode;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * AuthException类异常统一处理，因为项目是前后端分离的项目，异常捕捉后不能重定向，只返回json数组。
 */
@ControllerAdvice
public class AuthException {

    private ObjectMapper objectMapper =  new  ObjectMapper();//jackson工具

    @ExceptionHandler(value = UnauthorizedException.class)//处理访问方法时权限不足问题
    public void AuthcErrorHandler(HttpServletResponse res, Exception e) throws IOException {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_OK);
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/html; charset=utf-8");
        PrintWriter writer = res.getWriter();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", ResponseCode.PERMISSION_NO_ACCESS.code());
        map.put("msg", ResponseCode.PERMISSION_NO_ACCESS.message());
        writer.write(objectMapper.writeValueAsString(map));
        writer.close();
    }
}
